package com.henu.main.util;

import cn.hutool.json.JSONUtil;
import com.henu.main.entities.Metric;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.PushGateway;

import java.io.IOException;
import java.util.HashMap;

public class PushGateWayUtil {

    public static void push(Metric metric) {
        CollectorRegistry registry = null;
        Gauge gauge = null;
        try {
            PushGateway gateway = new PushGateway(Constant.PUSHGATEWAY_URL + ":9091");
            registry = new CollectorRegistry();
            gauge = Gauge.build().name("hadoop_service_metrics").help("Nothing").register(registry);
            HashMap<String, String> map = new HashMap<>();
            map.put("cluster", metric.getCluster());
            map.put("service", metric.getServiceName());
            map.put("metric", metric.getMetricName());
            map.put("hostname", metric.getHostname());
            gauge.set(metric.getValue());
            gateway.push(registry, "pushgateway", map);
            registry.unregister(gauge);
            System.out.println(TimeUtil.getNowDateString() + "：" + Thread.currentThread().getName() + "线程处理：" + metric);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (gauge != null) {
                gauge.clear();
            }
            if (registry != null) {
                registry.clear();
            }
        }
    }

    public static void push(HashMap map) {
        CollectorRegistry registry = null;
        Gauge gauge = null;
        try {
            PushGateway gateway = new PushGateway(Constant.PUSHGATEWAY_URL + ":9091");
            registry = new CollectorRegistry();
            gauge = Gauge.build().name("hadoop_service_metrics").help("Nothing").register(registry);
            gauge.set(Double.parseDouble(map.get("value").toString()));
            gateway.push(registry, "pushgateway", map);
            registry.unregister(gauge);
            System.out.println(TimeUtil.getNowDateString() + "：" + Thread.currentThread().getName() + "线程处理：" + JSONUtil.parseObj(map).toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (gauge != null) {
                gauge.clear();
            }
            if (registry != null) {
                registry.clear();
            }
        }
    }

}
